<!--智慧工地登录页-->
<template>
  <div class="psmbim-login">
    <!--头部-->
    <div class="login-header relative">
      <p class="login-p">碧桂园智慧工地</p>
      <img src="/static/images/project-title1.png" alt="">
    </div>

    <!--内容-->
    <div class="login-body" ref="loginBody">
      <div class="container clear">
        <div class="login-banner left">
          <div class="project-banner"></div>
        </div>
        <div class="login-box right">
          <div class="t-center login-box-header"></div>

          <!--帐号登录-->
          <div>
            <div class="login-form mb20">
              <input
                ref="username"
                v-validation="{required: true, query: 'username'}"
                type="text"
                v-model="username"
                placeholder="请输入BIP账号"
                @keydown="usernameKey">
            </div>

            <div class="login-form mb20">
              <input
                ref="password"
                v-validation="{required: true, query: 'password', min: 5}"
                type="password"
                placeholder="请输入密码"
                v-model="password">
            </div>

            <div class="login-form">
              <input
                style="width: 100px"
                v-validation="{required: true, query: 'checkCode'}"
                v-model="checkCode"
                placeholder="请输入验证码"
                @keydown="usernameKey"
                @keyup.enter="postLoginForm">
              <img class="checkCode" :src="src" v-tooltip="'点击换一张'" @click="loadCheckCode">
            </div>

          </div>

          <input type="button" value="登录" class="sub"  @click="postLoginForm">

          <p class="downVideo t-center"><a :href="`${this.$site.libServer}/OCX-OpenAPI.exe`">下载视频插件</a></p>

        </div>
      </div>
    </div>

    <div class="project-logo-bottom"></div>

  </div>
</template>

<script>
  import md5 from 'js-md5'
  export default {
    name: '',
    data () {
      return {
        username: '',
        password: '',
        phone: '',
        phoneCode: '获取验证码',
        checkCode: '',
        count: 60,
        captcha: '',
        isDisabled: false,
        dialogShow: true,
        loginTitle: '登录出错 ',
        loginTip: '短信登录',
        InterVal: null,
        isFirstQuery: false,
        dialogConfirm: '',
        ticket: '',
        coId: '',
        pjId: '',
        src: '',
        resolve: null,
        companyInfo: {},
        type: 1, // 进入的是企业层还是项目层 1： 企业层 2：项目层
        roleId: 1,
        project: [],
        roleType: {
          admin: false, // 部门管理员
          superAdmin: false, // 超级管理员
          advancedAdmin: false // 企业管理员
        },
        memberId: '',
        companyAndemployee: {}
      }
    },
    mounted () {
      window.document.title = '碧桂园智慧工地'
      this.loadCheckCode()
      if (this.$route.query.ticket) {
        this.ticket = this.$route.query.ticket
        this.ssoFinished()
      }
    },
    methods: {
      loadCheckCode () {
        this.src = `${this.$site.ssoServer}/sso/checkCode.do?d=${Math.random()}`
      },
      usernameKey (e) {
        if (e.which === 32) {
          e.returnValue = false
        }
        if (e.which === 13) {
          this.postLoginForm()
        }
      },
      // 帐号登录
      postLoginForm () {
        this.$vaildation(this).then(() => {
          if (this.isFirstQuery) {
            // this.$message.warning('请不要重复请求')
            return
          }
          this.isFirstQuery = true
          this.$store.commit('showLoading')
          // 对编码的字符串转化base64
          let password = ''
          if (this.testPhone(this.username)) {
            password = md5(this.password)
          } else {
            password = window.btoa(this.password)
          }
          this.$jsonp(`${this.$site.ssoServer}/sso/login/jsonp.do`,
            {
              'userName': this.username,
              'checkCode': this.checkCode,
              'password': password,
              'encodeType': 2,
              'forceCheck': 'true',
              'appKey': this.$site.appKey
            }
          ).then(json => {
            if (json.errorMsg) {
              this.loadCheckCode()
              this.$message.error(json.errorMsg)
              this.$store.commit('hideLoading')
              this.isFirstQuery = false
            } else {
              this.ticket = json.ticket
              let getCurrentUser = new this.$GetCurrentUser(json.ticket)
              getCurrentUser.ssoFinished().then((user) => {
                this.$local.set('login', 'projectLogin')
                this.getProjects(user).then((res) => {
                  // 没有项目权限
                  if (res[0] === 'company') {
                    this.getHasFuntion(user).then(res => {
                      if (res.hasFunction) {
                        this.findUserDataAccessRange(user).then(res => {
                          let dataAccessRange = res.data.dataAccessRange.code
                          if (res.data.dataAccessRange.code === 5) { // 进去企业大屏，数据权限是全集团
                            let currentCookie = JSON.parse(this.$getCookie('currentUser'))
                            currentCookie.companyAdmin = true
                            currentCookie.companyRoleRang = res.data.dataAccessRange.code
                            currentCookie.code = ''
                            currentCookie.departmentId = ''
                            currentCookie.companyTitle = '集团总部'
                            this.$setCookie('currentUser', JSON.stringify(currentCookie), {expires: 14, domain: this.$site.domain, path: '/'})
                            this.$router.push({name: 'company'})
                          } else { // 进去是企业大屏，数据权限是该区域
                            this.getAreaList(user).then(res => {
                              let currentCookie = JSON.parse(this.$getCookie('currentUser'))
                              currentCookie.companyAdmin = true
                              currentCookie.companyRoleRang = dataAccessRange
                              currentCookie.code = res.code
                              currentCookie.departmentId = res.departmentId
                              currentCookie.companyTitle = res.departmentName
                              this.$setCookie('currentUser', JSON.stringify(currentCookie), {expires: 14, domain: this.$site.domain, path: '/'})
                              this.$router.push({name: 'company'})
                            })
                          }
                        })
                      } else {
                        this.$message.error('没有权限')
                        this.loadCheckCode()
                        this.$store.commit('hideLoading')
                        this.isFirstQuery = false
                      }
                    })
                  } else {
                    let userInfo = res[1]
                    this.getHasFuntion(user).then(res => {
                      if (res.hasFunction) {
                        this.findUserDataAccessRange(user).then(res => {
                          let currentCookie = JSON.parse(this.$getCookie('currentUser'))
                          currentCookie.pjId = userInfo.projectId
                          currentCookie.pjName = userInfo.projectTitle
                          currentCookie.companyAdmin = true
                          currentCookie.companyRoleRang = res.data.dataAccessRange.code
                          this.$setCookie('currentUser', JSON.stringify(currentCookie), {expires: 14, domain: this.$site.domain, path: '/'})
                          this.$router.push({name: 'projectVideo'})
                        })
                      } else {
                        let currentCookie = JSON.parse(this.$getCookie('currentUser'))
                        currentCookie.pjId = userInfo.projectId
                        currentCookie.pjName = userInfo.projectTitle
                        currentCookie.companyAdmin = false
                        this.$setCookie('currentUser', JSON.stringify(currentCookie), {expires: 14, domain: this.$site.domain, path: '/'})
                        this.$router.push({name: 'projectVideo'})
                      }
                    })
                  }
                })
              }).catch(() => {
                this.loadCheckCode()
                this.$store.commit('hideLoading')
                this.isFirstQuery = false
              })
            }
          }).catch(() => {
            this.loadCheckCode()
            this.$store.commit('hideLoading')
            this.isFirstQuery = false
            this.$message.error('sso出错')
          })
        })
      },
      getHasFuntion (user, pjId) {
        return new Promise((resolve) => {
          let data = {}
          if (pjId) {
            data = {
              'query.project_id': pjId.projectId,
              'query.fun_code': 'p_ScreenBoardP'
            }
          } else {
            data = {
              'query.company_id': user.coId,
              'query.fun_code': 'c_ScreenBoard_browse'
            }
          }
          this.$axios({
            method: 'post',
            url: `${this.$site.companyServer}/front/hasFunction.htm`,
            data: this.$qs.stringify(data)
          }).then(res => {
            resolve(res.data)
          })
        })
      },
      getProjectList (user) {
        return new Promise(resolve => {
          const data = {
            'mid': user.mid,
            'coId': user.coId
          }
          this.$axios({
            method: 'post',
            closeLoading: true,
            url: `${this.$site.videoServer}/api/screen/getProjectList`,
            data: this.$qs.stringify(data)
          }).then(res => {
            if ((res.data.data).length > 0) {
              resolve(['project', res.data.data[0]])
            } else {
              resolve(['company'])
            }
          })
        })
      },
      // 获取企业大屏用户区域列表
      getAreaList (user) {
        return new Promise(resolve => {
          let data = {
            coId: user.coId,
            mid: user.mid
          }
          this.$axios({
            method: 'post',
            url: `${this.$site.videoServer}/api/companyScreen/getAreaList`,
            data: this.$qs.stringify(data)
          }).then(res => {
            resolve(res.data.data[0])
          })
        })
      },
      // 获取该用户的数据权限
      findUserDataAccessRange (user) {
        return new Promise(resolve => {
          let data = {
            'dataAccessRange.company_id': user.coId,
            'dataAccessRange.fun_code': 'c_ScreenBoard_browse'
          }
          this.$axios({
            method: 'post',
            url: `${this.$site.companyServer}/front/findUserDataAccessRange.htm`,
            data: this.$qs.stringify(data)
          }).then(res => {
            resolve(res)
          })
        })
      },
      // 获取该用户有权限的项目
      getProjects (user) {
        return new Promise(resolve => {
          const data = {
            'mid': user.mid,
            'coId': user.coId
          }
          this.$axios({
            method: 'post',
            closeLoading: true,
            url: `${this.$site.videoServer}/api/companyScreen/getProjects`,
            data: this.$qs.stringify(data)
          }).then(res => {
            if ((res.data.data).length > 0) {
              resolve(['project', res.data.data[0]])
            } else {
              resolve(['company'])
            }
          })
        })
      },
      testPhone (phone) {
        let phoneReg = /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/
        if (!phoneReg.test(phone)) {
          return false
        } else {
          return true
        }
      },
      findProjectList () {
        return new Promise(resolve => {
          const data = {
            'mid': this.companyAndemployee.mid,
            'coId': this.companyAndemployee.company_id,
            'departmentId': this.companyAndemployee.departmentId
          }
          this.$axios({
            method: 'post',
            url: `${this.$site.videoServer}/api/hikvision8700/getProjectPassCheckByAllVideos`,
            data: this.$qs.stringify(data)
          }).then(res => {
            this.project = res.data.data
            resolve()
          })
        })
      }
    }
  }
</script>
<style lang="scss" scoped>
  .psmbim-login{
    width: 100%;
    min-width: 1300px; // 1200+ 50*2 = 1300px
    .login-header{
      width: 534px;
      height: 93px;
      margin: 50px auto 0 auto;
      .login-p{
        position: absolute;
        top: 0;
        left: 70px;
        z-index: 1;
        color: #fff;
        font-size: 38px;
        letter-spacing: 10px;
      }
      img{
        width: 100%;
        position: absolute;
        top: 0;
        left: 0;
        z-index: 2;
      }
    }
    .login-body{
      width: 100%;
      margin-top: 0;
      .container{
        width: 1300px;
        padding: 80px 0;
        margin: 0 auto;
        position: relative;
        z-index:3;
        .login-banner{
          position: relative;
          .project-banner{
            position: absolute;
            width: 654px;
            height: 494px;
            background-image: url(/static/images/project-login-left.png);
            background-size: 100% 100%;
            left: 0;
            top: 0;
            z-index: -1;
          }
        }
        .login-box{
          width: 420px;
          height: 499px;
          padding: 30px 65px 45px 65px;
          box-sizing: border-box;
          background-image: url("/static/images/bgy-login.png");
          background-size: 100%;
          .login-box-header{
            width: 151px;
            height: 89px;
            margin: 30px auto 35px auto;
            background-image: url('/static/images/bgy-login-logo.png');
          }
          .login-form{
            height: 42px;
            line-height: 42px;
            border-radius: 3px;
            color: #999999;
            background: #f5f5f5;
            padding: 0 10px;
            border: 1px #3892ae solid;
            .checkCode{
              float: right;
              margin-top: 10px;
            }
            .iconfont{
              font-size: $font-size-large;
              color:  #999999;
            }
            span{
              display: inline-block;
              margin: 0 5px;
              vertical-align: top;
            }
            input {
              height: 100%;
              width: 270px;
              border:none;
              box-sizing: border-box;
              font-size: 12px;
              vertical-align: top;
              background: #f5f5f5;
              &:-webkit-autofill {
                -webkit-box-shadow: 0 0 0 1000px #f5f5f5 inset !important;
              }
            }
          }
          .login-phone{
            >span{
              font-size: $font-size-smallest;
              vertical-align: top;
            }
          }
          .sub{
            width: 100%;
            height: 45px;
            background: #0685ae;
            border:none;
            color: #fff;
            cursor: pointer;
            padding: 0;
            border-radius: 3px;
            margin-top: 28px;
            font-weight: bold;
            font-size: 18px;
            letter-spacing: 10px;
            text-indent: 10px;
            &:hover{
              background: $color-hover;
            }
          }
        }
      }
    }
    .downVideo{
      margin-top: 20px;
      cursor: pointer;
      a {
        color: #0ca8d9;
      }
    }
    .project-logo-bottom{
      position: fixed;
      bottom: 0;
      left: 0;
      background-image: url("/static/images/project-bottom.png");
      width: 1920px;
      height: 189px;
    }
  }
</style>
